﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using Presentation.ViewModel;
using CMS.Contracts;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.Text.RegularExpressions;


namespace Presentation
{
    public partial class StudentMainPage : System.Web.UI.Page
    {
        public int pageSize = 5;
        public int pageIndex = 1;
        public int pageCount;
        public int rowCount;    
        public void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                pageIndex = 1;
                ViewState["CurrentPage"] = pageIndex;
                InitStudentInfo(pageIndex, pageSize);
            }
        }

        protected void PageNavaigage_Click(Object sender, EventArgs e)
        {
            LinkButton btn = (LinkButton)sender;
            string cmdName = btn.CommandName;
            pageCount = ((int)ViewState["rowCount"] + pageSize - 1) / pageSize;
            switch (cmdName)
            { 
                case "First":
                    ViewState["CurrentPage"] = 1;
                    break;
                case "Previous":
                    ViewState["CurrentPage"] = (int)ViewState["CurrentPage"] - 1;
                    break;
                case "Next":
                    ViewState["CurrentPage"] = (int)ViewState["CurrentPage"] + 1;
                    break;
                case "Last":
                    ViewState["CurrentPage"] = pageCount;
                    break;
            }
            pageIndex = (int)ViewState["CurrentPage"];
            InitStudentInfo(pageIndex, pageSize);
        }

        protected void SetButtonState(int pageindex)
        {
            pageCount = ((int)ViewState["rowCount"] + pageSize - 1) / pageSize;
            if (pageindex <=1)
          {
            btnFirst.Enabled = false;
            btnPre.Enabled = false;
          }
           else
         {
            btnFirst.Enabled = true;
            btnPre.Enabled = true;
         }
            if (pageindex >= pageCount)
           {
               btnNext.Enabled = false;
               btnLast.Enabled = false;
           }

           else
           {
               btnNext.Enabled = true;
               btnLast.Enabled = true;
           }
        }
        protected void btnSkip_Click(object sender, EventArgs e)
        {
            string regPatten = "/^[0-9]+$/";
           //string regPatten="/^\\[0-9]{3}|1[0-9]{3}$/";
           // string regPatten="/^(0|[1-9]\\d\\d|1000)$/";
            Regex reg = new Regex(regPatten);
            string aa=txtSkipPage.Text.Trim();
            if (txtSkipPage.Text.Trim() == string.Empty)
            {
                return;
            }
            else
            {
                int skipPage = int.Parse(txtSkipPage.Text.Trim());
                if (skipPage > ((int)ViewState["rowCount"] + pageSize - 1) / pageSize)
                {
                    txtSkipPage.Text = string.Empty;
                    pageCount = ((int)ViewState["rowCount"] + pageSize - 1) / pageSize;
                    this.pageIndex = pageCount;
                    ViewState["CurrentPage"] = pageIndex;
                    InitStudentInfo(pageIndex, pageSize);
                    btnNext.Enabled = false;
                    btnLast.Enabled = false;
                }
                else if (skipPage < 1)
                {
                    txtSkipPage.Text = string.Empty;
                    this.pageIndex = 1;
                    ViewState["CurrentPage"] = pageIndex;
                    InitStudentInfo(pageIndex, pageSize);
                    btnFirst.Enabled = false;
                    btnPre.Enabled = false;
                }
                else
                {
                    this.pageIndex = skipPage;
                    ViewState["CurrentPage"] = pageIndex;
                    InitStudentInfo(pageIndex, pageSize);
                }
            }
            txtSkipPage.Text = "";
      
            //else if (!(reg.Match(aa).Success))
            //{
            //    lblWarnMessage.Text = "Not valid,just input positive number";
            //}
            //else if (int.Parse(txtSkipPage.Text.Trim()) > 1000)
            //{
            //    lblWarnMessage.Text = "Not valid,just the length is less than 1000";
            //}

        }


        private void InitStudentInfo(int pageIndex, int pageSize)
        {
            using (ChannelFactory<IProjectBService> channelFactory = new ChannelFactory<IProjectBService>("CMSClient"))
            {
                IProjectBService channel = channelFactory.CreateChannel();
                List<CMS.Model.Student> student = channel.GetAllStudents(pageIndex, pageSize,out rowCount);
                List<StudentCourseDetailView> studentCourseDetailViewList = new List<StudentCourseDetailView>();
                StudentCourseDetailView studentCourseDetailView;
                foreach (CMS.Model.Student obj in student)
                {
                    studentCourseDetailView = new StudentCourseDetailView();
                    studentCourseDetailView.ClassName = obj.Grade.ClassName;
                    studentCourseDetailView.StudentGender = obj.StudentGender;
                    studentCourseDetailView.StudentId = obj.StudentId;
                    studentCourseDetailView.StudentName = obj.StudentName;
                    studentCourseDetailViewList.Add(studentCourseDetailView);
                }
                gvStudentInfo.DataSource = studentCourseDetailViewList;
                gvStudentInfo.DataBind();
                ViewState["rowCount"] = rowCount;
            }

            lblRowsCount.Text = string.Format("Total Records：{0}", rowCount);
            lblPagesIndex.Text = string.Format("Current/Total：{0}/{1}", pageIndex, (rowCount + pageSize - 1)/pageSize);
            SetButtonState(pageIndex);
        }

        protected void btnaddStudent_Click(object sender, EventArgs e)
        {
            Boolean type = true;
            Response.Redirect("ManageStudent.aspx?type=" + type);
        }

        protected void gvStudentInfo_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int StudentId = Convert.ToInt32(gvStudentInfo.DataKeys[e.RowIndex].Value);
            DeleteStudentInfo(StudentId);

        }

        private void DeleteStudentInfo(int StudentId)
        {
            using (ChannelFactory<IProjectBService> channelFactory = new ChannelFactory<IProjectBService>("CMSClient"))
            {
                IProjectBService channel = channelFactory.CreateChannel();
                pageCount = ((int)ViewState["rowCount"] + pageSize - 1) / pageSize;
                pageIndex = (int)ViewState["CurrentPage"];
                try
                {
                    if ((int)ViewState["rowCount"]% 5 == 1 && pageIndex == pageCount)
                    {
                        channel.DeleteStudentById(StudentId);
                        pageIndex = pageIndex - 1;
                    }
                    else
                        channel.DeleteStudentById(StudentId);


                }
                catch(FaultException<InvalidOperationException> ioe)
                {
                    TextBox1.Text = ioe.Message;
                }

                if (pageIndex > pageCount)
                {
                    pageIndex = pageCount;
                }
                else
                    if (pageIndex < 1)
                    {
                        pageIndex = 1;
                    }
               
                InitStudentInfo(pageIndex, pageSize);
            }
        }

        protected void gvStudentInfo_RowEditing(object sender, GridViewEditEventArgs e)
        {
            string studentId = this.gvStudentInfo.DataKeys[e.NewEditIndex].Value.ToString();
            Boolean type = false;
            Response.Redirect("ManageStudent.aspx?id=" + studentId + "&type=" + type);
        }
    }
}
